﻿// Shader-Based-Image-Processing (SBIP)
// http://code.google.com/p/sbip/
//
// Copyright © Frank Nagl, 2009-2010
// admin@franknagl.de
//
namespace SBIP.Filter
{
    using System;
    using Microsoft.Xna.Framework.Graphics;
    using System.Drawing.Imaging;
    using CommonAlgorithms = Grayscale.CommonAlgorithms;
    using Versions = FixedGaussianBlur.Versions;

    public sealed class CannyEdgeDetector : BaseFilter
    {
        // 462.750458f / 255 belongs to Cathedral.jpg
        private float maxGradient;
        private byte lowThreshold;
        private byte highThreshold;

        #region effect properties
        /// <summary>If true, the filter results in an black-white image.</summary>
        public bool BlackWhite { get; set; }
        /// <summary>
        /// Defines the grayscale algorithm type. 
        /// See also <seealso cref="Grayscale.CommonAlgorithms"/>.
        /// </summary>
        public CommonAlgorithms GrayscaleAlgorithm { get; set; }

        /// <summary>The version of Gaussian blur filter. 
        /// Further informations: <see cref="FixedGaussianBlur.Versions"/></summary>
        public Versions Version { get; set; }

        /// <summary>
        /// Maximal gradient value, [0.1, 5.65].
        /// </summary>
        /// 
        /// <remarks><para>Gradient value for non-maximum-suppression calculation.</para>
        /// 
        /// <para>Default value is set to <b>1.8147</b>.</para>
        /// </remarks>
        /// 
        public float MaxGradient
        {
            get { return maxGradient; }
            set
            {
                // get new maxGradient value
                maxGradient = (float)Math.Max(0.1, Math.Min(5.65, value));
            }
        }

        /// <summary>
        /// Low threshold for Canny algorithm.
        /// </summary>
        /// 
        /// <remarks><para>Low threshold value used for hysteresis
        /// (see  <a href="http://www.pages.drexel.edu/~weg22/can_tut.html">tutorial</a>
        /// for more information).</para>
        /// 
        /// <para>Default value is set to <b>20</b>.</para>
        /// </remarks>
        /// 
        public byte LowThreshold
        {
            get { return lowThreshold; }
            set
            {
                if (Effect == null)
                    throw new ArgumentException("LowThreshold" + InitMsg);
                // get new low threshold value
                lowThreshold = value;
                Effect.Parameters["LowThreshold"].SetValue(value);
            }
        }

        /// <summary>
        /// High threshold for Canny algorithm.
        /// </summary>
        /// 
        /// <remarks><para>High threshold value used for hysteresis
        /// (see  <a href="http://www.pages.drexel.edu/~weg22/can_tut.html">tutorial</a>
        /// for more information).</para>
        /// 
        /// <para>Default value is set to <b>100</b>.</para>
        /// </remarks>
        /// 
        public byte HighThreshold
        {
            get { return highThreshold; }
            set
            {
                if (Effect == null)
                    throw new ArgumentException("HighThreshold" + InitMsg);
                // get new high threshold value
                highThreshold = value;
                Effect.Parameters["HighThreshold"].SetValue(value);
            }
        }
        #endregion effect properties

        /// <summary>
        /// Initializes a new instance of the <see cref="CannyEdgeDetector"/> class.
        /// </summary>
        public CannyEdgeDetector() : base("CannyEdgeDetector") { }

        private Texture2D GetGrayscaleTex()
        {
            Effect e = GetExternalEffect("Grayscale");
            switch (GrayscaleAlgorithm)
            {
                case CommonAlgorithms.BT709:
                    e.Parameters["Red"].SetValue(0.2125f);
                    e.Parameters["Green"].SetValue(0.7154f);
                    e.Parameters["Blue"].SetValue(0.0721f);
                    break;
                case CommonAlgorithms.RMY:
                    e.Parameters["Red"].SetValue(0.5f);
                    e.Parameters["Green"].SetValue(0.419f);
                    e.Parameters["Blue"].SetValue(0.081f);
                    break;
                case CommonAlgorithms.Y:
                    e.Parameters["Red"].SetValue(0.299f);
                    e.Parameters["Green"].SetValue(0.587f);
                    e.Parameters["Blue"].SetValue(0.114f);
                    break;
            }
            Texture2D grayscale = _RenderEffectToTexture(e, "Grayscale");
            return grayscale;
        }

        private Texture2D GetNonMaxSuppressTex()
        {
            // Step 0 - make image/texture grayscale
            Texture2D grayscale = GetGrayscaleTex();

            // STEP 1 - blur image
            Effect e = GetExternalEffect("FixedGaussianBlur");
            e.Parameters["Version"].SetValue((byte)Version);
            Texture2D blur = _RenderEffectToTexture(grayscale, e, "FixedGaussianBlur", SurfaceFormat.Color);
            //ImageConverter.TextureToRGB(blur).Save("canny-vergleich/blur-sbip.bmp", ImageFormat.Bmp);

            // STEP 2-5 - calculate gradients (sobel operator), finding edge direction, nonmaximum suppression
            e = GetExternalEffect("CannyNonmaximumsuppression");
            e.Parameters["MaxGradient"].SetValue(MaxGradient);
            Texture2D tex = 
                _RenderEffectToTexture(blur, e, "CannyNonmaximumsuppression", SurfaceFormat.Color);
            return tex;
        }

        /// <summary>Renders the specified effect.</summary>
        internal override void RenderEffect()
        {
             Texture2D nonmaximumsuppression = GetNonMaxSuppressTex();
            // STEP 6 - hysteresis
            Effect.Parameters["ImageTexture"].SetValue(nonmaximumsuppression);
            Technique = BlackWhite ? "HysteresisBW" : "Hysteresis";
            base.RenderEffect();
        }

        /// <summary>Renders the specified effect into a texture.</summary>
        /// <returns>The rendered texture.</returns>
        internal override Texture2D RenderEffectToTexture()
        {
            Texture2D nonmaximumsuppression = GetNonMaxSuppressTex();
            //ImageConverter.TextureToRGB(nonmaximumsuppression).Save("canny-vergleich/nonmaximumsuppression-sbip.bmp", ImageFormat.Bmp);
            // STEP 6 - hysteresis
            Technique = BlackWhite ? "HysteresisBW" : "Hysteresis";
            Texture2D hysteresis = _RenderEffectToTexture(nonmaximumsuppression);
            //ImageConverter.TextureToRGB(hysteresis).Save("canny-vergleich/hysteresis-sbip.bmp", ImageFormat.Bmp);
            return hysteresis;
        }

        /// <summary>
        /// Defines Laplace algorithm properties.
        /// </summary>
        protected override void PostInit()
        {
            MaxGradient = 1.8147f;
            LowThreshold = 20;
            HighThreshold = 100;
        }
    }
}
